package com.ruoyi.yuwen.controller;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.github.pagehelper.PageInfo;
import com.ruoyi.common.newAdd.returnResult.Data;
import com.ruoyi.common.newAdd.returnResult.Res;
import com.ruoyi.common.newAdd.utils.TimeUtil;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.yuwen.domain.Order;
import com.ruoyi.yuwen.domain.User;
import com.ruoyi.yuwen.service.IUserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.yuwen.domain.Apply;
import com.ruoyi.yuwen.service.IApplyService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 升级申请审核Controller
 * 
 * @author ruoyi
 * @date 2023-04-20
 */
@RestController
@RequestMapping("/yuwen/apply")
public class ApplyController extends BaseController
{
    @Autowired
    private IApplyService applyService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private IUserService userService;

    /**
     * 查询升级申请审核列表
     */
    @PreAuthorize("@ss.hasPermi('yuwen:apply:list')")
    @GetMapping("/list")
    public TableDataInfo list(Apply apply)
    {
        startPage();
        List<Apply> list = applyService.selectApplyList(apply);
        return getDataTable(list);
    }

    /**
     * 导出升级申请审核列表
     */
    @PreAuthorize("@ss.hasPermi('yuwen:apply:export')")
    @Log(title = "升级申请审核", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Apply apply)
    {
        List<Apply> list = applyService.selectApplyList(apply);
        ExcelUtil<Apply> util = new ExcelUtil<Apply>(Apply.class);
        util.exportExcel(response, list, "升级申请审核数据");
    }

    /**
     * 获取升级申请审核详细信息
     */
    @PreAuthorize("@ss.hasPermi('yuwen:apply:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(applyService.selectApplyById(id));
    }

    /**
     * 新增升级申请审核
     */
    @PreAuthorize("@ss.hasPermi('yuwen:apply:add')")
    @Log(title = "升级申请审核", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Apply apply)
    {
        return toAjax(applyService.insertApply(apply));
    }

    /**
     * 修改升级申请审核
     */
    @PreAuthorize("@ss.hasPermi('yuwen:apply:edit')")
    @Log(title = "升级申请审核", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Apply apply)
    {
        return toAjax(applyService.updateApply(apply));
    }

    @PostMapping("/update")
    public AjaxResult update(@RequestBody Apply apply)
    {
        if (apply.getState()==1){
            User temp = new User();
            temp.setUserLevel(101l);
            List<User> list = userService.selectUserList(temp);
            if (list.size()<=0){
                return AjaxResult.error("审核失败，请重试。");
            }
            User user = userService.selectUserById(apply.getUserId());
            user.setUserLevel(102l);
            user.setFatherId(list.get(0).getId());
            userService.updateUser(user);
        }
        return toAjax(applyService.updateApply(apply));
    }

    /**
     * 删除升级申请审核
     */
    @PreAuthorize("@ss.hasPermi('yuwen:apply:remove')")
    @Log(title = "升级申请审核", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(applyService.deleteApplyByIds(ids));
    }

    /** 前端接口 **************************************************************************************************** */
    /** 前端接口 **************************************************************************************************** */
    /** 前端接口 **************************************************************************************************** */

    /**
     * 添加申请
     * @param apply
     * @return
     */
    @PostMapping("/front/applyAdd")
    public Res applyAdd(@RequestBody Apply apply){

        Long userId = tokenService.getUserId();
        User user = userService.selectUserById(userId);

        Apply temp = new Apply();
        temp.setUserId(user.getId());
        temp.setState(0);
        List<Apply> list = applyService.selectApplyList(temp);
        if (list.size()>0){
            return Res.okShowMsg("已提交申请，请勿重复提交");
        }

        apply.setUserId(user.getId());
        apply.setUserName(user.getName());
        apply.setAddtime(TimeUtil.getStringTime("yyyy-MM-dd HH:mm:ss"));
        apply.setState(0);

        applyService.insertApply(apply);

        return Res.okShowMsg("申请提交成功！");
    }

    /**
     * 个人申请列表
     * @return
     */
    @GetMapping("/front/applyList")
    public Res applyList(){

        Long userId = tokenService.getUserId();
        User user = userService.selectUserById(userId);

        Apply apply = new Apply();
        apply.setUserId(user.getId());

        startPage();
        List<Apply> list = applyService.selectApplyList(apply);

        return Res.ok().put("data", Data.ok().put("list",list).put("total",new PageInfo(list).getTotal()));
    }

    /**
     * 个人申请详情
     * @return
     */
    @GetMapping("/front/applyInfo")
    public Res applyInfo(@RequestParam("id")Long id){

        Apply apply = applyService.selectApplyById(id);

        return Res.ok().put("data", Data.ok().put("apply",apply));
    }
}
